package c3;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.IntPredicate;
import java.util.function.Predicate;

public class FunctionInterfaceTest {
    public static void main(String[] args) {
        //test Predicate
        Predicate<String> nonEmptyStringPredicate=s->!s.isEmpty();
        List<String> stringList= Arrays.asList("a","","aaa");
        for(String s:stringList){
            if(nonEmptyStringPredicate.test(s)){
               System.out.println(s);
            }
        }

        //test consumer
        forEach(Arrays.asList(1,2,3,4), System.out::println);

        //test function
        List<Integer> sLengthList=map(Arrays.asList("1","11","111"),String::length);
        System.out.println(sLengthList);

        IntPredicate intPredicate=i->i%2==0;
        System.out.println(intPredicate.test(1000));

        System.out.println("函数复合测试-Function");
        Function<Integer,Integer> f=x->x=x+1;
        Function<Integer,Integer> g=x->x=x*2;
        //g(f())
        Function<Integer,Integer> h=f.andThen(g);
        //f(g())
        Function<Integer,Integer> j=f.compose(g);

        int result1=h.apply(1);
        int result2=j.apply(1);
        System.out.println(result1);
        System.out.println(result2);
    }

    public static <T> void forEach(List<T> list, Consumer<T> c){
        for(T t:list){
            c.accept(t);
        }
    }

    public static <T,R> List<R> map(List<T> list, Function<T,R> f){
        List<R> result=new ArrayList<>();
        for(T t:list){
            result.add(f.apply(t));
        }
        return result;
    }

    public static  void integerPreTest(List<Integer> list,Predicate<Integer> i){
        //比较慢的循环来测试
        for(int j=0;j<list.size();j++){
            if(i.test(list.get(j))){
               //do something
            }
        }
    }
}
